package com.chineseall.app.service;

import javax.annotation.Resource;

import jmind.core.mongodb.MongoCollection;
import jmind.core.util.DataUtil;

import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import com.chineseall.app.dao.mongo.AppMachine;
import com.chineseall.app.dao.mongo.AppVersion;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

@Service
public class MachineService {
    @Resource
    AppMachine ppgMachine;
    @Resource
    AppVersion appVersion;

    public synchronized ObjectId getMachineId(BasicDBObject jo) {
        ObjectId machineId = ppgMachine.getMachineId(jo.getString("mid"));
        if (machineId == null) {
            ppgMachine.insert(jo);
            machineId = jo.getObjectId(MongoCollection.ID);
        }
        return machineId;
    }

    public DBObject getMachine(String mid) {
        return ppgMachine.getMachine(mid);
    }

    public void updateMachine(ObjectId id, DBObject update) {
        ppgMachine.update(new BasicDBObject("_id", id), update);
    }

    public void updateMachine(String mid, DBObject update) {
        ppgMachine.update(new BasicDBObject("mid", mid), update);
    }

    /**
     * 
     * @param version null 取当前版本
     * @param os  平台 1 android、2 iphone
     * @return
     */
    public DBObject getVersion(String version, String os, String channel) {
        if (DataUtil.isEmpty(os))
            return appVersion.findOne(null);
        if (DataUtil.isEmpty(version)) {
            return appVersion.getCurrentVersion(os, channel);
        }
        return appVersion.getVersion(version, os, channel);
    }

    public int getVersionVal(String version) {
        String v = DataUtil.getInt(version);
        return DataUtil.toInt(v) * 100;
    }

}
